package com.github.gaojh.example.websocket;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.gaojh.ioc.annotation.WebSocket;
import com.github.gaojh.server.handler.WebSocketAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @author gaojh
 * @since 2020/3/26
 */
@WebSocket("/test")
@Slf4j
public class WebSocketHandler implements WebSocketAdapter {

    private static final AttributeKey<String> HOST = AttributeKey.newInstance("host");

    @Override
    public void onHandshake(ChannelHandlerContext ctx, FullHttpRequest fullHttpRequest) throws Exception {
        String host = fullHttpRequest.headers().get("host");
        log.info("有新的连接：{}", host);
        ctx.channel().attr(HOST).set(host);
        WebSocketContext.addChannel(host, ctx.channel());
    }

    @Override
    public void onMessage(ChannelHandlerContext ctx, String msg) throws Exception {
        sendMessage(ctx, msg);
    }

    @Override
    public void onClose(ChannelHandlerContext ctx) throws Exception {
        System.out.println("onClose");
        WebSocketContext.delChannel(ctx.channel().attr(HOST).get());
    }

    @Override
    public void onException(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println(ctx.channel().attr(HOST).get());
        WebSocketContext.delChannel(ctx.channel().attr(HOST).get());
    }
}
